using UnityEngine;

public class ShockStrikeController : MonoBehaviour
{
    private static readonly int Hit = Animator.StringToHash("hit");
    private Animator anim;
    private CharacterStats targetStats;
    [SerializeField] private float speed;
    private bool triggered;
    private int damage;

    private void Awake()
    {
        anim = GetComponentInChildren<Animator>();
    }

    private void Update()
    {
        if (!targetStats)
        {
            return;
        }
        if (triggered)
        {
            return;
        }
        transform.position = Vector3.MoveTowards(transform.position, targetStats.transform.position, speed * Time.deltaTime);
        transform.right = transform.position - targetStats.transform.position; // Rotate towards the target
        if (!(Vector2.Distance(transform.position, targetStats.transform.position) < 0.1f)) return;
        anim.transform.localPosition = new Vector3(-0.13f, 0.4f, 0); // Reset position to avoid unwanted translations
        anim.transform.localRotation = Quaternion.identity;
        transform.localRotation = Quaternion.identity; // Reset rotation to avoid unwanted rotations
        transform.localScale = new Vector3(3, 3); // Reset scale to avoid unwanted scaling
        Invoke(nameof(DamageAndSelfDestroy), 0.2f); // Call DamageAndSelfDestroy after a short delay
        triggered = true;
        anim.SetTrigger(Hit);
    }

    public void Setup(int damage, CharacterStats targetStats)
    {
        this.damage = damage;
        this.targetStats = targetStats;
    }

    private void DamageAndSelfDestroy()
    {
        targetStats.ApplyShock(true);
        targetStats.TakeDamage(damage); // Assuming TakeDamage is a method in CharacterStats that handles damage
        Destroy(gameObject, 0.4f); // Destroy the thunderstrike after hitting the target
    }
}
